﻿// -----------------------------------------------------------------------------
// DM 是 .NET 5 平台下开发管理的系统。
// Copyright © 2021 DM,  Co.,Ltd.
//
// 框架名称：Furion
// 后台框架：ABC.Admin
// -----------------------------------------------------------------------------

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Tool
{
    public static class WebExtensions
    {
        /// <summary>
        /// 获取当前域名
        /// </summary>
        /// <param name="httpContext">当前http上下文</param>
        /// <returns></returns>
        public static string GetDomain(this HttpContext httpContext) => new StringBuilder()
                              .Append(httpContext.Request.Scheme)
                              .Append("://")
                              .Append(httpContext.Request.Host).ToString();
        
        /// <summary>
        /// 获取用户 Id
        /// </summary>
        public static T GetLoginUserId<T>(this HttpContext httpContext)
        {
            if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
            {
                if (httpContext.User.Claims.Any(o => o.Type == ClaimTypes.Sid))
                {
                    var v = httpContext.User.FindFirst(ClaimTypes.Sid).Value;
                    return v.To<T>();
                }
            }
            return default(T);

        }
        /// <summary>
        /// 获取用户 账户
        /// </summary>
        public static string GetLoginUserAccount(this HttpContext httpContext)
        {
            return httpContext.User.Identity.Name;
        }

        /// <summary>
        /// 获取用户 UserNick
        /// </summary>
        public static string GetLoginUserNick(this HttpContext httpContext)
        {
            if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
            {
                if (httpContext.User.Claims.Any(o => o.Type == ClaimTypes.Name))
                {
                    var v = httpContext.User.FindFirst(ClaimTypes.Name).Value;
                    return v.To<string>();
                }
            }
            return httpContext.GetLoginUserAccount();

        }

    }
}
